package com.it.you.base.designmode.proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * CgLib主要是基于类进行代理
 */
public class CglibProxy1 {
    public static void main(String[] args) {
        //创建被代理的对象
        PeopleService target = new PeopleService();
        Enhancer enhancer = new Enhancer();
        //设置代理类
        enhancer.setSuperclass(PeopleService.class);
        enhancer.setCallback(new MethodInterceptor() {
            /**
             * 方法拦截器
             * @param o
             * @param method  代理对象正在执行的方法
             * @param objects 执行当前方法所传的参数
             * @param methodProxy
             * @return
             * @throws Throwable
             */
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                if (method.getName().equals("work")) {
                    System.out.println("before...");
                    //target 被代理的对象 执行需要代理的方法逻辑
                    method.invoke(target, objects);
                    System.out.println("after...");
                    return null;
                }
                return method.invoke(target, objects);
            }
        });
        //创建代理对象
        PeopleService peopleService = (PeopleService) enhancer.create();
        peopleService.work();
    }
}
